package com.anysdk.sms.demo.controller;

import com.anysdk.sms.demo.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/login")
@CrossOrigin(origins = "*")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping("/send-code")
    public ResponseEntity<?> sendCode(@RequestBody Map<String, String> request) {
        String phone = request.get("phone");
        if (phone == null || phone.isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "手机号不能为空"));
        }
        
        try {
            String code = loginService.sendCode(phone);
            return ResponseEntity.ok(Map.of("success", true, "message", "验证码发送成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "验证码发送失败：" + e.getMessage()));
        }
    }

    @PostMapping("/verify")
    public ResponseEntity<?> verifyCode(@RequestBody Map<String, String> request) {
        String phone = request.get("phone");
        String code = request.get("code");
        
        boolean isValid = loginService.verifyCode(phone, code);
        
        if (isValid) {
            return ResponseEntity.ok(Map.of("success", true, "message", "验证成功"));
        } else {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "验证码错误"));
        }
    }
} 